//
//  UIColor+Extension.swift
//  Utility
//
//  Created by 于虎拴 on 2022/10/21.
//

import Foundation
import UIKit

public extension UIColor {
  convenience init(_ hex: String) {
    let hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines)
    let scanner = Scanner(string: hexString)
    
    if hexString.hasPrefix("#") {
      scanner.currentIndex = scanner.string.index(scanner.string.startIndex, offsetBy: 1)
    }
    
    var color: UInt64 = 0
    scanner.scanHexInt64(&color)
    
    let mask = 0x000000FF
    let r = Int(color >> 16) & mask
    let g = Int(color >> 8) & mask
    let b = Int(color) & mask
    
    let red = CGFloat(r) / 255.0
    let green = CGFloat(g) / 255.0
    let blue = CGFloat(b) / 255.0
    
    self.init(red: red, green: green, blue: blue, alpha: 1)
  }
  
  convenience init(hex: Int, alpha: CGFloat = 1.0) {
    self.init(
      red: CGFloat((hex >> 16) & 0xFF) / 255.0,
      green: CGFloat((hex >> 8) & 0xFF) / 255.0,
      blue: CGFloat(hex & 0xFF) / 255.0,
      alpha: alpha
    )
  }
  
  // UIColor -> Hex String
  var hexString: String {
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    
    // multiplier
    let multi = CGFloat(255)

    guard self.getRed(&r, green: &g, blue: &b, alpha: &a) else {
      return ""
    }
    
    if a == 1.0 {
      return String(format: "#%02X%02X%02X", Int(r * multi), Int(g * multi), Int(b * multi))
    } else {
      return String(format: "#%02X%02X%02X%02X", Int(r * multi), Int(g * multi), Int(b * multi), Int(a * multi))
    }
  }
}
